package com.ruigi.Filter;
//检查用户是否完成登录

import com.alibaba.fastjson.JSON;
import com.ruigi.common.Basecontext;
import com.ruigi.pojo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginfilter", urlPatterns = "/*")
@Slf4j
public class Loginfilter implements Filter {
    //路径匹配器
    public static final AntPathMatcher PATH = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("拦截到" + request.getRequestURL());
        String requestURI = request.getRequestURI();
        String[] strings = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/druid/**"


        };


        boolean check = check(strings, requestURI);
        if (check) {
            filterChain.doFilter(request, response);
            return;

        }
        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录，用户id为：{}", request.getSession().getAttribute("employee"));

            Long empId = (Long) request.getSession().getAttribute("employee");
            Basecontext.setid(empId);

            filterChain.doFilter(request, response);
            return;
        }
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录，用户id为：{}", request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            Basecontext.setid(userId);

            filterChain.doFilter(request, response);
            return;
        }
        log.info("用户未登录");
        //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;


        //判断本次请求是否需要处理


    }

    public boolean check(String[] uls, String url) {
        for (String ul : uls) {
            boolean match = PATH.match(ul, url);
            if (match) {
                return true;
            }

        }

        return false;
    }
}
